package com.three.aboutus.utils;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author ：JinShiYan
 * @date ：Created in 2024/12/17 16:11
 * @description：
 * @modified By：
 * @version:
 */
public class Upload {
    public static String upload(MultipartFile myfile, HttpServletRequest request) throws IOException {
        //1.获取保存文件的路径
        String realPath = request.getSession().getServletContext().getRealPath("/images");
        //2.根据上面的路径创建文件对象
        File file = new File(realPath);
        //3.判断该文件夹是否存在
        if (!file.exists()) {
            file.mkdirs();
        }
        //4.获取上传文件的名称. 获取登录者ip+登录者id+登录者的时间戳
        String filename = UUID.randomUUID().toString().replace("-", "") + myfile.getOriginalFilename();
        //5.把上传的文件保存到指定服务器下的路径。
        File target = new File(realPath + "/" + filename);
        myfile.transferTo(target);
        return "main";
    }

    public static String uploadOss(MultipartFile myfile) {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        //   EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        DefaultCredentialProvider defaultCredentialProvider = CredentialsProviderFactory.newDefaultCredentialProvider("\n" +
                "LTAI5t9BpBKBJSqbT49tuYU6", "3h1YqFmYOJvWazUo5hxYa10UMLsvxw");
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "qy179";
        // 填写Object完整路径，完整路径中不能包含Bucket名称 上传到oss的bucket中的名称
        String objectName = UUID.randomUUID().toString().replace("-", "") + myfile.getOriginalFilename();
        // 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。
        // 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
        // 填写Bucket所在地域。以华东1（杭州）为例，Region填写为cn-hangzhou。
        String region = "cn-beijing";

        // 创建OSSClient实例。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(defaultCredentialProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            InputStream inputStream = myfile.getInputStream();
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            return "https://" + bucketName + "." + endpoint + "/" + objectName;
        }  catch (Exception ce) {
            throw new RuntimeException("上传失败");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
